package com.fare.taluo.core.domain.crawl.adapter.sub;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.Source;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.fare.taluo.conf.ConfigContainer;
import com.fare.taluo.core.domain.config.city.PortEntity;
import com.fare.taluo.core.domain.config.line.FlightInfoEntity;
import com.fare.taluo.core.domain.crawl.CrawlCSAirLineModel;
import com.fare.taluo.core.domain.crawl.adapter.AbstractAdapter;
import com.fare.taluo.util.DateUtils;
import com.fare.taluo.util.StringAndDateAndFileUtil;

/**
 * 东方航空航线验证适配器
 * @author zengxiangqi
 *
 */
public class CEAirLineAdaptor extends AbstractAdapter{
	private HttpClient client = null;
	private String cookeiStr;
	private String referer;
	
	public CEAirLineAdaptor(CrawlCSAirLineModel portModel){
		super(portModel);
	}
	@Override
	public List<Object> paraseToVo(Object fetchObject) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public String getUrl() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public Object fetch(String url) throws Exception {
		HttpClient httpclient = new DefaultHttpClient(); 
		HttpPost httppost = new HttpPost("http://easternmiles.ceair.com/addservice/aoc!queryNewFlightStatus.shtml"); 

		
// Add your data 
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
			nameValuePairs.add(new BasicNameValuePair("arrivalPot", portModel.getToCity())); 
			nameValuePairs.add(new BasicNameValuePair("departPort", portModel.getFromCity())); 
			nameValuePairs.add(new BasicNameValuePair("flightTime", ".")); 
			nameValuePairs.add(new BasicNameValuePair("qType", "1")); 
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

// Execute HTTP Post Request 
			HttpResponse response = httpclient.execute(httppost); 

			InputStream is = response.getEntity().getContent(); 
			BufferedInputStream bis = new BufferedInputStream(is); 
			ByteArrayBuffer baf = new ByteArrayBuffer(20); 

			int current = 0; 
			while((current = bis.read()) != -1){ 
				baf.append((byte)current); 
			} 

			String text = new String(baf.toByteArray(),"utf-8"); //指定编码
			
			
			//String temp = text.substring(text.indexOf("(")+1, text.lastIndexOf(")"));
			
			return text;
		/*	System.out.println(temp);
			System.out.println(result);
			JSONObject jb = new JSONObject(result);
			JSONArray array = jb.getJSONArray("data");
			System.out.println(array.length());
			JSONObject object = (JSONObject) array.get(0);
			System.out.println(object.get("flightno"));*/
		/*String s;
		try {
			setReferer("http://www.ceair.com/mu/main/index.html");
			setReferer("http://easternmiles.ceair.com/aoc/index.html");
			fetchURI(produceWaittingUri());
			setRequestDatas();
			setReferer("http://easternmiles.ceair.com/aoc/index.html");
			s = fetchURI(produceUri());
			return s;
		} finally {
			referer = null;
			cookeiStr = null;
			client = null;
		}*/
	}
	
	private URI produceUri() throws URISyntaxException {
		return (new URIBuilder())
				/*.addParameter("inter", "331")
				.addParameter("isInter", "331")*/
				.addParameter("flightTime", ".")
				.addParameter("qType", "1")
				.addParameter("arrivalPot", portModel.getToCity())
				.addParameter("departPort", portModel.getFromCity())
				.addParameter("newCond.queryByType", portModel.getQueryType())
				.setScheme("http").setHost("easternmiles.ceair.com")
				.setPath("/addservice/aoc!queryNewFlightStatus.shtml").build();
		//http://easternmiles.ceair.com/aoc/index.html
	}
	
	private URI produceWaittingUri() throws URISyntaxException {
		/*return this.produceUri();*/
		/*URI uri = new URIBuilder()
		.addParameter("inter", "331")
		.addParameter("isInter", "331")
		.addParameter("newCond.queryFlightDate", ".")
		.addParameter("day1", "2")
		.addParameter("newCond.queryArrivalPot", portModel.getToCity())
		.addParameter("newCond.queryDepartPort", portModel.getFromCity())
		.addParameter("newCond.queryByType", portModel.getQueryType())
		.setScheme("http")
		.setHost("easternmiles.ceair.com").setPath("/addservice/aoc!queryNewFlightStatus.shtml")
		.build();
		return uri;*///http://eb.csair.com/flightQuery/fltQueryETicketResultN.jsp
		URI uri = new URIBuilder()
		//.addParameter("doaction", "/aoc/index.html")
		.addParameter("flightTime", ".")
		.addParameter("qType", "1")
		.addParameter("_", "1381286902819")
		.addParameter("arrivalPot", portModel.getToCity())
		.addParameter("departPort", portModel.getFromCity())
		//.addParameter("newCond.queryByType", portModel.getQueryType())
		.setScheme("http").setHost("easternmiles.ceair.com")
		.setPath("/addservice/aoc!queryNewFlightStatus.shtml").build();
		return uri;
	}
	
	private String fetchURI(URI uri) throws Exception {
		HttpPost request;
		HttpEntity entity;
		byte data[];
		request = null;
		HttpResponse response = null;
		entity = null;
		InputStream is = null;
		data = null;
		String s;
		try {
			if (client == null)
				client = super.getHttpClient();
			client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,1000000);
		        //响应超时
			client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000000);
			request = new HttpPost(uri);
			request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			request.setHeader("Accept-Encoding", "gzip, deflate");
			request.setHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
			request.setHeader("Connection", "keep-Alive");
			request.setHeader("Content-Type",
					"text/html; charset=UTF-8");
			if (StringUtils.isNotBlank(cookeiStr))
				request.setHeader("Cookie", cookeiStr);
			request.setHeader("Host", "easternmiles.ceair.com");
			request.setHeader("User-Agent",
					"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0");
			request.setHeader("Referer", referer);
			response = client.execute(request);
			entity = response.getEntity();
			if (entity != null) {
				is = entity.getContent();
				data = writeByte(is);
			}
			
			s = new String(data, "UTF-8");
		//	System.out.println(s);
		} finally {
			if (is != null)
				try {
					is.close();
				} catch (Exception e) {
				}
			;
			is = null;
			if (request != null)
				request.releaseConnection();
			if (entity != null)
				EntityUtils.consume(entity);
			entity = null;
			response = null;
			request = null;
		}
		return s;
	}
	
	/*private List<Object> parseSource(Source source,Map<String,PortEntity> map) {
		List<Object> dataList = new ArrayList<Object>();
		List<Element> elementList = source.getAllElementsByClass("flight_search_table");
        for (Iterator iterator = elementList.iterator(); iterator.hasNext();) {
			Element element = (Element) iterator.next();
			List<Element> trLists = element.getAllElementsByClass("flight_search_tr");
			if(null == trLists||trLists.size()==0){
				return null;
			}else{
				for (Iterator iterator2 = trLists.iterator(); iterator2.hasNext();) {
					Element trElement = (Element) iterator2.next();
					List<Element> tdList = trElement.getChildElements();
					FlightInfoEntity entity = new FlightInfoEntity();
					entity.setFlightNo(tdList.get(0).getTextExtractor().toString());//设置航班号
					if(null != map.get(super.portModel.getFromCity())){//机场是否存在
				    	//设置出发地名称
				    	entity.setFromCityName(map.get(super.portModel.getFromCity()).getCityName());
				    	//设置出发地代号
				    	entity.setFromCity(super.portModel.getFromCity());
				    }
				    if(null != map.get(super.portModel.getToCity())){//机场是否存在
				    	//设置出发地名称
				    	entity.setToCityName(map.get(super.portModel.getToCity()).getCityName());
				    	//设置出发地代号
				    	entity.setToCity(super.portModel.getToCity());
				    }
					
				    String[] depTime = tdList.get(3).getTextExtractor().toString().split(" ");
				    String[] arrTime = tdList.get(5).getTextExtractor().toString().split(" ");
				    //判断是否第二天才到达
				    try {
				    	 if(null!=depTime && depTime.length>0 && arrTime.length>0 && depTime[0].equals(arrTime[0])){
				    		   entity.setFlightStartTime(depTime[1]);
						    	entity.setFlightEndTime(arrTime[1]);
						    	//设置航班日期
							    entity.setFlightDate(depTime[0].substring(4, 6)+"-"+depTime[0].substring(6, 8));
						    }else if(null!=depTime && depTime.length>0 && arrTime.length>0){
						    	//第二天到达
						    	 entity.setFlightStartTime(depTime[1]);
						    	entity.setFlightEndTime(arrTime[1]+"+1");
						    	//设置航班日期
							    entity.setFlightDate(depTime[0].substring(4, 6)+"-"+depTime[0].substring(6, 8));
						    }    
					} catch (Exception e) {
						 e.printStackTrace();
					}
				   
				   
				    //设置航班日期
				   // entity.setFlightDate(depTime[0].substring(4, 6)+"-"+depTime[0].substring(6, 8));
				    entity.setCompanyCode("MU");
					entity.setCompanyName("东方航空");
					entity.setEntryTime(new Date());
					dataList.add(entity);			
				}
			}
			
			
		
		}		
		return dataList;
	}*/
	
	public List<Object> paraseToVo(Object fetchObject,Map<String,PortEntity> map) throws JSONException {
		JSONObject jb = null;
		String fetchStr = fetchObject.toString();
		List<Object> dataList = new ArrayList<Object>();
		String temp = fetchStr.substring(fetchStr.indexOf("(")+1, fetchStr.lastIndexOf(")"));
		String result =  "{"+"\"data\":"+temp+"}";
 		//若返回数据为空值，则直接返回
		if("[]".equals(temp) || "".equals(temp)){
 			return null;
 		}
		//若出发地或目的地不在数据库中，则直接返回
		if(null == map.get(super.portModel.getFromCity()) || null == map.get(super.portModel.getToCity())){
			return null;
		}
		
		
		try {
			jb = new JSONObject(result);
		
		JSONArray array = jb.getJSONArray("data");
		for (int i = 0; i < array.length(); i++) {
			JSONObject object = (JSONObject) array.get(i);
			FlightInfoEntity entity = new FlightInfoEntity();
			entity.setFlightNo((String) object.get("flightno"));
			entity.setFromCityName(map.get(super.portModel.getFromCity()).getCityName());
	    	//设置出发地代号
	    	entity.setFromCity(super.portModel.getFromCity());
	    	
	    	entity.setToCityName(map.get(super.portModel.getToCity()).getCityName());
	    	//设置目的地代号
	    	entity.setToCity(super.portModel.getToCity());
			String flightStartTime = (String) object.get("etd");
			entity.setFlightStartTime(flightStartTime.split(" ")[1]);
			String flightEndTime = (String)object.get("eta");
			entity.setFlightEndTime(flightEndTime.split(" ")[1]);
	   	    entity.setCompanyCode("MU");
			entity.setCompanyName("东方航空");
			entity.setEntryTime(new Date());
			dataList.add(entity);
			
			//System.out.println(object.get("flightno"));
		}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return dataList;
		
		
		
		
		
		
		
		//以下是东方航空旧版官网代码
		/*String tempResult = fetchObject.toString();
		List<Object> list = parseSource(new Source(tempResult),map);
		tempResult = null;
		return list;*/
	}
	
	private void setRequestDatas() {
		AbstractHttpClient aclient = (AbstractHttpClient) client;
		List<Cookie> cookies = aclient.getCookieStore().getCookies();
		StringBuilder sbuilder = new StringBuilder();
		Cookie c;
		for (Iterator<Cookie> iterator = cookies.iterator(); iterator.hasNext(); sbuilder
				.append(c.getName()).append("=").append(c.getValue())
				.append(";"))
			c = (Cookie) iterator.next();

		cookeiStr = sbuilder.toString();
	}
	@Override
	public boolean validateFetch(Object fetchObject) throws Exception {
		// TODO Auto-generated method stub
		return false;
	}
	public HttpClient getClient() {
		return client;
	}
	public void setClient(HttpClient client) {
		this.client = client;
	}
	public String getCookeiStr() {
		return cookeiStr;
	}
	public void setCookeiStr(String cookeiStr) {
		this.cookeiStr = cookeiStr;
	}
	public String getReferer() {
		return referer;
	}
	public void setReferer(String referer) {
		this.referer = referer;
	}
	
	public static void main(String[] args) throws Exception {
		CrawlCSAirLineModel portModel = new CrawlCSAirLineModel();
		portModel.setFromCity("PVG");
		portModel.setToCity("AAA");
		portModel.setQueryType("1");
		ConfigContainer.getInstance().register("com.fare.taluo.core.domain.crawl.CrawlPropertiesLoader");
		CEAirLineAdaptor adap = new CEAirLineAdaptor(portModel);
		Object obj = adap.fetch(null);
		//String text = new String(obj.toString().getBytes("UTF-8"),"GBK");
		if(!obj.toString().contains("您查询的航班不存在")){
			//System.out.println(obj.toString());
			//删除<script>..</script>
//			String parseStr = Pattern.compile("<script.*?>.*?</script>", Pattern.CASE_INSENSITIVE).matcher(obj.toString()).replaceAll("<td>");  
//			List<Object> results = adap.paraseToVo(parseStr);
//			System.out.println(results.size());
			List<Object> results = adap.paraseToVo(obj.toString(),new HashMap<String, PortEntity>());
		}
		
	}
	
	
	
	
	
}



